<?php
	require_once("include/common.php");
?>



<!DOCTYPE html>
<html lang="en" ng-app="deviceApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

<title>表计列表</title>

	<?php
		require_once("pages/resources.php");
	?>
<!-- 
	<link href="/meter/resources/bootstrap-3.3.6/css/bootstrap.min.css" rel="stylesheet">
 -->
	<script src="/meter/resources/jquery/jquery-2.0.3.js"></script>
	<script src="/meter/resources/js/jquery.jeditable.lk.js"></script>
 	<script src="/meter/resources/angular-1.5.5/angular.js"></script>
 	<script src="/meter/resources/js-base-util.js"></script>
 	<script type="text/javascript" src="/meter/resources/layer/layer.js"></script>
</head>
<body class="sidebar-narrow"  id="deviceCtrl" ng-controller="deviceCtrl">

	<!-- Navbar -->
	 
	<?php
		require_once("pages/navbar.php");
	?>
	<!-- /navbar -->


	<div class="page-container sidebar-hidden">

		<!-- Sidebar -->
		 
		<?php
			require_once("pages/siderbar.php");
		?>
		<!-- /sidebar -->


		<!-- Begin: Content -->
		<div class="page-content">

			<!-- Page header -->
            <div class="page-header">
                <div class="datatable-header">
                	<div style="    margin-top:30px">
						<div id="DataTables_Table_0_filter" class="dataTables_filter" style="width: 40%">
							<label>
							 
								<input type="text" id="_queryInput" placeholder="输入查询关键字..." name="search" class="form-control" 
					                        ng-model="q" ng-change="change()"
					                             autocomplete="off"> 
							</label>
						</div>

						<div   style="display: table-cell; width: 10% ">
		                        <b>Date:</b> <select id="dateSelect" ng-model="type"  ng-change="change();">
		                        	<option value="">All</option>
		                        	<option value="V">Virtual</option>
		                        	<option value="P">Meter</option>
		                        </select>
		                </div>


						<label class="col-sm-2 control-label"> 上传Excel文件（<a href="templates/USERS.xls">下载模板</a>）  </label>
					 
						<div class="dataTables_length" id="DataTables_Table_0_length" style="width: 40%">
							 
							<div class="uploader" id="uploadDiv">
								<input type="file" name="file" size="50" class="styled" onchange="uploadFiles();">
								<span class="filename" style="-webkit-user-select: none;">No file selected</span>
								<span class="action" style="-webkit-user-select: none;">Choose File</span>
							</div>
					 
							
						</div>
					</div>
				</div>

				 
          
            </div>
            <!-- /page header -->

	       
             <div class="panel panel-default" >
                <div class="panel-heading">
                	<h6 class="panel-title"><i class="icon-table2"></i> 电表数据维护 </h6>
                </div>
            	<div class="table-responsive">
		 
		
         
	            	<table class="table table-striped table-bordered" >
						<thead>
							<tr>
								<td> 表计代码  </td>
								<td> 地址 </td>
								<td> 使用者  </td>
								<td> 类型  </td>
								<td> 标签  </td>
								<td> 更新 </td>
								<td> 最后数值(KWh)  </td>
								<td> 最后数值时间  </td>
								<td> 操作  </td>
						    </tr>
						</thead>
						<tbody>

							<tr ng-repeat="meter in meters">
					    		<td>
					    			<a href="meter-data.php?meter={{meter._METER}}" >
					    				{{meter._METER}}
					    			</a>
					    		</td>
					    		<td id="{{meter._METER}}" class="editable">{{meter._NAME}}</td>
					    		<td>  
					    		 
					    			<select class="form-control" ng-model="getMeter(meter._METER)._USERID" ng-change="updateMeter(meter._METER,getMeter(meter._METER)._USERID)">
										<option ng-repeat="user in users" value="{{user.user}}">{{user.name}}</option>
									</select>

					    		</td>
					    		<td>{{ getMeterType(meter._METERTYPE) }}</td>
					    		<td>{{  meter._TAGS }}</td>
					    		<td>{{meter._UPDATED}}</td>
					    		<td>{{meter._VALUE}}</td>
					    		<td>{{meter._LAST}}</td>
					    		<td style="">
					    			<center>
					    			<a href="#" ng-click="removeMeter(meter._METER)">
					    			<i class="icon-remove"></i>
					    			</a>

					    			&nbsp;&nbsp;
					    			<a href="#" ng-click="showDialog(meter._METER , meter._METERTYPE);" title="编辑"> <i class="icon-wrench2"></i> </a>


					    			</center>
					    		</td>
					    	</tr>
						</tbody>					
					</table>
					
				</div>
				<div class="panel-footer" style="padding-top: 10px">
			 			<div style="float: left">
						<!-- 	Size : <span>{{meters.length}}</span> -->
						</div>
						<div style="position: relative; float: right; right: 20px; top: 0px;padding-bottom: 10px">

							<a href="#" ng-if="begin>0" ng-click="page(-1);">Previous</a>
							<span ng-if="begin==0" style="color: lightgrey">Previous</span>
							-
							<a href="#" ng-if="meters.length==size" ng-click="page(1);">Next</a>
							<span ng-if="meters.length<size" style="color: lightgrey">Next</span>
						</div>	
					</div>
			</div>

 	        <!-- Footer -->
	         
	        <?php
				require_once("pages/footer.php");
			?>
	        <!-- /footer -->

		</div>
		<!-- End: Content -->

 


	</div>

	<div style="position: fixed; bottom: 0px ; right: 0px; z-index: 999">
             
        <span id="responseId" class="label ">
            success!
        </span>
      
    </div>

</body>
<script type="text/javascript">

	var users =  null;

	function response_status( command , result ){
		if(result.status == 0 ){
			$('#responseId').removeClass('label-warning');
			$('#responseId').addClass('label-success');
			$('#responseId').text( 'success! ' + command);
		}else {
			$('#responseId').removeClass('label-success');
			$('#responseId').addClass('label-warning');
			
			$('#responseId').text( 'Error : ' + result.status + ' ' + result.message + '\n' + command );
		}
	}
	

	function bindEditable() {

		$(".editable").editable('/meter/rest/disp.php?m=metername', {
			 
			onresult : function(value , current , revert ) {
				if( value ) {
					var obj = JSON.parse(value);

					response_status( 'update user name ...' + current , obj );

					if(obj && obj.status == 0 )
					{
						var ctrl = angular.element('#deviceCtrl');
        				var $scope= ctrl.scope();
        				$scope.setMeterName( obj.result.meter, obj.result.name );
        				// return '';

						return obj.result.name ;
					}else {
						return   revert ;
					}
				}
		       return   value;
		   	},
            type: 'text',//实时编辑input框的type
            cancel: '取消',//取消编辑按钮的文字
            submit: '确定',//确认提交按钮的文字
            indicator: '保存中...',//提交处理过程中显示的提示文字
            placeholder: '<span style="color:green">单击编辑...</span>',//鼠标悬停时的提示信息
            
        });

	}
	 

    var app = angular.module('deviceApp', []);
    app.controller('deviceCtrl', 
    	function($scope, $http, $timeout) {
        	$scope.q = '' ;
        	$scope.type = '' ;
        	$scope.begin = 0 ;
     		$scope.size  = 10 ;
        	$scope.last  = 0 ;
        	$scope.users =  [] ; 
            $scope.meters = [] ;
            $scope.count  = 1 ;
             
            var stop = null ;

            $scope.showNewMeterDialog =function(){
                _showDialog('', '');
            }
	  		
            $scope.showDialog =function(meter , type ){
                _showDialog(meter , type == 'V' ? '1' : '');
            }


            $scope.getMeterType = function(type){
            	if( type == undefined || type == '' || type == null )
            		return '物理';
            	if( type == 'V' )
            		return '虚拟';
            	else if( type == 'P')
            		return '物理';
            	else
            		return type;
            }
            $scope.getMeter = function(meterId){
            	for (var i = 0; i < $scope.meters.length; i++) {
            		if( meterId == $scope.meters[i]._METER) {
            			return $scope.meters[i];
            		}
            	}
            	return null;
            }
 		
 			$scope.page= function( dir ){
        		if(dir>0){
        			if( $scope.meters.length == $scope.size)
        				$scope.begin += $scope.size;	
        			else
        				return ;

        		}else {

        			$scope.begin -=$scope.size;
        			if( $scope.begin <0 )
        				$scope.begin = 0;
        		}
        		

              	$scope.loadMeters();
            }  
  
	  
         	$scope.change= function(){
         		$scope.begin = 0 ;
              	$scope.loadMeters();
            }  

            $scope.setMeterName = function( meterId , name ){
            	var mt = $scope.getMeter(meterId);
            	if(mt)
            		mt._NAME = name;
            }

            $scope.loadUsers = function() {
                
            
 
                var url = '/meter/rest/disp.php?m=userlist'  ;
                               
                
                $http.get( url )
                    .success(
                        function(response) 
                        {

                            response_status( 'Loading user :' , response );

                            if( response.status != 0 )
                            {
                                return ;
                            }

                            response = JSON.retrocycle(response);
                            $scope.users = [];
                            $scope.users.push( { user: '', name:  ''});
                            for( var i = 0 ; i <response.result.length ;i++ ){
                            	var user = response.result[i];
                             
                            	$scope.users.push( { user: user._USERID, name: user._NAME });
                            	 
                            }
                           	

                        }
              );
            }; 

            $scope.removeMeter = function( meter  ) {
                
                var index = layer.confirm('您正在试图删除电表 ' + meter + '， 这种操作是不可逆的，你要继续吗? ', {
				  btn: ['是的','取消'] //按钮
				}, function(){
					layer.close(index);
				  	$scope.removeMeter0(meter);
				}, function(){
				  
				});


          
            };    

            $scope.removeMeter0 = function( meter  ) {
              	
                var url = '/meter/rest/disp.php?m=meterremove'  ;
                // var url = "/rest/api/data/devRT?" ;

				url = _appendUrlList( url, "meter" , meter );
			        
                
                $http.get( url )
                    .success(
                        function(response) 
                        {
                        	response_status( 'remove meter :' + meter  ,  response );
                            $scope.loadMeters ();
                        }
              );
            };      

            $scope.updateMeter = function( meter, userid ) {
                
              
                var url = '/meter/rest/disp.php?m=updatemeter'  ;
                // var url = "/rest/api/data/devRT?" ;

				url = _appendUrlList( url, "meter" , meter );
				url = _appendUrlList( url, "user" , userid  );
		            
                
                $http.get( url )
                    .success(
                        function(response) 
                        {
                        	response_status( 'update meter :' + meter +"/"+ userid, response );
                            
                        }
              );
            };   
		 
            $scope.loadMeters = function() {
                
              
                var url = '/meter/rest/disp.php?m=meterlist'  ;
   				url = _appendUrlList( url, "q" , $scope.q  );
   				url = _appendUrlList( url, "type" , $scope.type  );
   				 
                url = _appendUrlList( url, "begin" , $scope.begin  );
   			 	url = _appendUrlList( url, "size" , $scope.size   );
                $http.get( url )
                    .success(
                        function(response) 
                        {

                            response_status( 'load meters ... ' + $scope.q, response );
                            if( response.status != 0 )
                            {  
                                return ;
                            }

                            response = JSON.retrocycle(response);

                           	$scope.meters = response.result ;


                           	$timeout((function() {
							      bindEditable();
							}), 0);


                        }
              );
            };   

                // init 
            $scope.loadUsers();
            $scope.loadMeters();
            
  
        });

    function uploadFiles() {
   		var file = $('input[name="file"').get(0).files[0];
   		if( !file )
   			return ;
		var formData = new FormData();
		formData.append('file', file);

		var htmlv = $('#uploadDiv').html();
		$('#uploadDiv').html(htmlv);

		$.ajax({
		  url : '/meter/rest/disp.php?m=upload_meters',
		  type : 'POST',
		  data : formData,
		  cache : false,
		  contentType : false,
		  processData : false,
		  success : function( result , textStatus, jqXHR) {
		   // var result = JSON.parse(jqXHR.responseText);
		    // alert(userObj);
		    if(result.status == 0 ){
		    	reloadMeters();
		    }else {
		    	alert( jqXHR.responseTex );
		    }
		  },
		  error : function(jqXHR, textStatus, errorThrown) {
		    alert(textStatus);
		  }
		});
   }


    function reloadMeters(  ){
        var ctrl = angular.element('#deviceCtrl');
        var $scope= ctrl.scope();
 
        $scope.loadMeters();
    }



	function _showDialog(meter , virtual ){
	    
	    var url = "meter-edit.php?id=" + meter +"&virtual=" + virtual ;
	    layer.open({
	      type: 2,
	      title: false , // meter ? '编辑电表信息' : '新增电表',
	      shadeClose: true,
	      shade: 0.8,
	      area: ['800px', '60%'],
	      content: [ url    ] //iframe的url
	    });
	   
	}


</script>
</html>
